package com.nw.news.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.nw.news.AppContext;
import com.nw.news.R;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.utils.FileUtil;

public class MainActivity extends BaseFrameworkActivity {

	private MainMenuFragment mainMenuFragment;
	private MainVideoFragment mainVideoFragment;
	private MainMyFragment mainMyFragment;
	// 当前显示的fragment的index
	private int currentTabIndex = 0;
	private Fragment[] fragments;
	private TextView[] mTabs;

	private long mExitTime;// 退出时间
	private static final int INTERVAL = 2000;// 退出间隔

	@Override
	protected int getLayoutId() {
		return R.layout.activity_main;
	}

	@Override
	protected void bindViews() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加禁止系统扫描图片的文件
		FileUtil.createFile(AppContext.getSavePath() + "/.nomedia");
		initTab();
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
//		AppUpdate.getInstance().cancel();//释放检查更新的下载
	}

	/**
	 * 初始化tab页
	 */
	private void initTab() {
		mTabs = new TextView[]{findViewById(R.id.tab_1), findViewById(R.id.tab_2), findViewById(R.id.tab_3)};
		// 把第一个tab设为选中状态
		mTabs[currentTabIndex].setSelected(true);
		mainMenuFragment = new MainMenuFragment();
		mainVideoFragment = new MainVideoFragment();
		mainMyFragment = new MainMyFragment();
		fragments = new Fragment[]{mainMenuFragment, mainVideoFragment, mainMyFragment};
		getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragments[currentTabIndex]).show(fragments[currentTabIndex]).commit();

//		getNotificationData();
	}

	/**
	 * tab点击事件
	 */
	public void onTabClicked(View view) {
		int index = Integer.parseInt(view.getTag().toString()) - 1;
		if (currentTabIndex != index) {
			FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
			trx.hide(fragments[currentTabIndex]);
			if (!fragments[index].isAdded()) {
				trx.add(R.id.fragment_container, fragments[index]);
			}
			trx.show(fragments[index]).commit();
		} else {
			return;
		}
		mTabs[currentTabIndex].setSelected(false);
		// 把当前tab设为选中状态
		mTabs[index].setSelected(true);
		currentTabIndex = index;
	}

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - mExitTime > INTERVAL) {
			Toast.makeText(this, "再按一次返回键,可直接退出程序", Toast.LENGTH_SHORT).show();
			mExitTime = System.currentTimeMillis();
		} else {
			closeSelf();
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
			// moveTaskToBack(true);// 进入后台。
		}
	}

	/**
	 * activityResult传递事件,用于传递给fragment
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
}
